package com.zhufeng.gateway.db.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @ClassName: MsgPathGatewayFilterFactor
 * @Description 消息路径转发
 * @author 月夜烛峰
 * @date 2022/9/16 18:45
 */
@Slf4j
@Component
public class MsgPathGatewayFilterFactory extends AbstractGatewayFilterFactory<MsgPathGatewayFilterFactory.Config> {

    public MsgPathGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(MsgPathGatewayFilterFactory.Config config) {
        return new GatewayFilter() {

            @Override
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                log.info("自定义过滤器...");
                ServerHttpRequest req = exchange.getRequest();
                ServerHttpRequest request = req.mutate().path(config.getNewPath()).build();
                exchange.getAttributes().put(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR, request.getURI());
                return chain.filter(exchange.mutate().request(request).build());
            }
        };
    }

    public static class Config {

        private String newPath;

        public String getNewPath() {
            return newPath;
        }

        public Config setNewPath(String newPath) {
            this.newPath = newPath;
            return this;
        }

    }


}